﻿<%@ Page Title="调拨工具" Language="C#" MasterPageFile="~/master/m.master" %>

<script runat="server"></script>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <link href="../assets/css/plugins/footable/footable.core.css" rel="stylesheet">
    <link href="../assets/css/shelf/base.css" rel="stylesheet">
    <link href="../assets/css/plugins/webuploader/webuploader.css" rel="stylesheet" />
    <link href="../assets/img/validate/validate.css" rel="stylesheet">
    <link href="../assets/css/plugins/boxdrop/boxDrop.css" rel="stylesheet" />
    <link href="../assets/css/plugins/bootstrap-select/bootstrap-select.min.css" rel="stylesheet" />
    

    <style type="text/css">
.system-box .right-side {width: 100%;}
.condition, .condition-title {border-bottom: 1px solid #dfdfdd;}
.condition .form-control {padding: 2px 6px;}
.module-info td .control-label {margin-right: 0px;width: 70px;}
td {border-top: 1px solid #929292 !important;padding: 1px !important;}
th, .tips {padding: 1px !important;}
.DropTd { /*border: 1px solid #e7eaec;*/border: 2px solid red !important;}
.RedText {color: red;}
.BlueText, .afterStatus {color: blue;}
/*.loadTable {width: initial;}*/
.NotAllowOut {background-color: rgba(139, 195, 74, 0.39);cursor: default !important;}
.NotAllowIn {background-color: rgba(26, 179, 148, 0.19);cursor: default !important;}
.NotAllowAll {background-color: #ccc;cursor: default !important;}
.divTitle {display: inline-block;border: 1px solid #ccc;background-color: #ddd;padding: 2px;margin-right: 3px;margin-top: 3px;-moz-border-radius: 5px;-webkit-border-radius: 5px;border-radius: 5px;}
.tips {line-height: normal;color: #bc7b21;background: #fffdcd;padding: 5px;border-bottom: 1px solid #e5e5e5;}
body {-webkit-touch-callout: none;-webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;}
.stockBox {height: 35px;display:none;border-left: 1px solid #ccc;}
.stockTableBox {float: left;position: relative;top: -2px;padding-left: 5px;}
.stockTableBox table tr td, .stockTableBox table tr th {padding: 0 5px !important;}
.total{ font-weight: bold;}
.btn-default {color: #333 !important;background: #fff !important;border-color: #ccc;}
.form-search-commodity{ width: 102px !important;}
.form-search-province{ width: 138px !important;}
.form-search-city{ width: 107px !important;}
.dropdown-menu>li>a {margin: 4px !important; }
.boxSearch .bootstrap-select.btn-group.show-tick .dropdown-menu li.selected a span.check-mark {font-size: 16px;color: rgb(44, 143, 123);}
.bootstrap-select.btn-group.show-tick .dropdown-menu li a span.text {margin-right: 0px;}
.infomation{ border: 0px;padding-top: 10px !important;display: none;height: 34px;float: left;margin-right: 10px;}
.seriesName{ padding-right: 3px;}
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="main" runat="Server">
    <div class="system-box">
        <div class="right-side">
            <div class="btns-container">
            </div>
            <div class="condition clearfix">
                <label>货号</label>
                <input id="search-MaterialID" class="form-control input-w155" value="" />
                <label>店铺&nbsp;&nbsp;</label>
                <input class="" id="search-Shop" placeholder="输入店铺名称或编号" style="display: none;" />
                <div class="infomation">
                    <span>系列：</span><span class="seriesName"></span>
                    <span>小品类：</span><span class="itemName"></span>
                </div>
                <span class="stockBox">
                    <label for="search-stockID">仓库：</label>
                    <select class="form-control input-w110" id="search-stockID">
                        <option value="">请选择</option>
                    </select>
                    <span class="stockTableBox">
                        <table class="table table-bordered text-center ">
                            <thead></thead>
					<tbody></tbody>
                           <%-- <tr>
                                <td>尺码</td>
                                <td>S</td>
                                <td>M</td>
                                <td>L</td>
                                <td>XL</td>
                            </tr>
                            <tr>
                                <td>库存</td>
                                <td>11</td>
                                <td>11</td>
                                <td>11</td>
                                <td>11</td>
                            </tr>--%>
                        </table>
                    </span>
                </span>
            </div>
            <div class="tips"><i class="fa fa-lightbulb-o"></i>"店铺"支持拖拽操作，已经是调出店铺时不能再被选为调出方，"上市天数"14天内或"在途"为"Y"时不能作为调出方，"调出"为"Y"时不能作为调入方.</div>

            <div class="right-content-box">
                <div class="ibox-content">
                    <table class="footable table table-stripped table-list loadTable">
                        <thead></thead>
                        <tbody id="pageList"></tbody>
                    </table>
                </div>
            </div>
            <%--        <div class="pageControl"></div>--%>
        </div>
    </div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="footer" runat="Server">
    <script src="../assets/img/validate/learunui-validator.js"></script>
    <script src="../assets/js/page/pageControl.js"></script>
    <script src="../assets/js/page/rScroll.js"></script>
    <script src="../assets/js/page/tableControl.js"></script>
    <script src="../assets/js/plugins/webuploader/webuploader.min.js"></script>
    <script src="../assets/js/framework.js"></script>
    <script src="../assets/js/plugins/bootstrap-select/bootstrap-select.min.js"></script>
    <script src="../assets/js/plugins/bootstrap-select/i18n/defaults-zh_CN.min.js"></script>
    <script src="../assets/js/plugins/bootstrap-typeahead/bootstrap-typeahead.js"></script>
    <script src="../assets/js/plugins/boxdrop/jquery.boxdrop2.js"></script>
    <script src="../assets/js/jquery-ui-1.10.4.min.js"></script>
    <script src="../assets/js/plugins/jquery.ui.widgets/customdroppable.js"></script>
    <script src="../assets/js/plugins/linq/jquery.linq.min.js"></script>

    <script>
        //$('p:textEquals("dmhai")');
        $.expr[':'].textEquals = $.expr.createPseudo(function (arg) {
            return function (elem) {
                return $(elem).text().match("^" + arg + "$");
            };
        });
        //$('p:textLessThanOrEqualTo(5)');
        $.expr[':'].textLessThanOrEqualTo = $.expr.createPseudo(function (num) {
            return function (elem) {
                var text = $(elem).text().trim();
                return parseInt(text) <= num;
            };
        });
        //$('p:textMoreThan2(5)');
        $.expr[':'].textMoreThan2 = $.expr.createPseudo(function (num) {
            return function (elem) {
                var text = $(elem).text().trim();
                if (text.indexOf("/") == -1) {
                    return false;
                }
                var right = text.split("/")[1];
                return parseInt(right) > num;
            };
        });
        //$('p:textMoreThan(5)');
        $.expr[':'].textMoreThan = $.expr.createPseudo(function (num) {
            return function (elem) {
                var text = $(elem).text().trim();
                return parseInt(text) > num;
            };
        });
        //双行列开始索引（说明列,在动态尺码列前面）
        var iColumn = 9;
        $('document').ready(function () {
            //模块ID
            var ModuleID = Y.getUrlParam("ModuleID");
            //当前页数
            var page = 1;
            commonUtil.loadBtnList(ModuleID, function () {
                rScroll();
            });

            //绑定 仓
            //绑定
            if ($("#search-stockID-step3 option").length <= 1) {
                $("#search-stockID-step3").html('<option value="">请选择</option>');
                commonUtil.bindOdsErpBasStocks2({}, ['#search-stockID']); //配货仓库
            }

            //处理表头
            if ($('.footable thead').children().size() == 0) {
                tableControl.initThead('.footable',
                [
                    {
                        trClass: '',
                        children: [
                            { tdText: '公司', c: 0, r: 0, tdHtml: '', tdId: '', tdClass: 'hide diy-td-w72' },
                            { tdText: '仓库ID', c: 0, r: 0, tdHtml: '', tdId: '', tdClass: 'hide diy-td-w72' },
                            { tdText: '店铺', c: 0, r: 0, tdHtml: '', tdId: '', tdClass: 'diy-td-w200' },
                            { tdText: '上市天数', c: 0, r: 0, tdHtml: '', tdId: '', tdClass: 'diy-td-w72' },
                            { tdText: '货号', c: 0, r: 0, tdHtml: '', tdId: '', tdClass: 'hide diy-td-w100' },
                            { tdText: '销售状态', c: 0, r: 0, tdHtml: '', tdId: '', tdClass: 'diy-td-w72' },
                            { tdText: '在途', c: 0, r: 0, tdHtml: '', tdId: '', tdClass: 'diy-td-w30' },
                            { tdText: '流转周', c: 0, r: 0, tdHtml: '', tdId: '', tdClass: 'diy-td-w46' },
                            { tdText: '调出', c: 0, r: 0, tdHtml: '', tdId: '', tdClass: 'diy-td-w46' },
                            { tdText: '状态', c: 0, r: 0, tdHtml: '', tdId: '', tdClass: 'diy-td-w46' },
                            { tdText: '说明', c: 0, r: 0, tdHtml: '', tdId: '', tdClass: 'SizeFlag diy-td-w46' },
                            { tdText: '合计', c: 0, r: 0, tdHtml: '', tdId: '', tdClass: 'diy-td-w46' },
                            { tdText: '调出店铺', c: 0, r: 0, tdHtml: '', tdId: '', tdClass: '' }
                        ]
                    }
                ]);
            };
            var dragTr = null;
            var loadList = function () {
                pageControl.init('NewOdsErpTmpCalcStock', 'GetOdsErpTmpCalcStock', {
                    MaterialID: $('#search-MaterialID').val(),
                    ShopIDs: $('#search-Shop').val(),
                    Page: page,
                    Size: 10000,
                    needLayer: true,
                    alwaysCallBack: function () {
                    }
                }, function (result) {
                    $('#btn-save').removeAttr("disabled");
                    page = result.page;
                    var tBody = []; 
                    if (!Y.checkNull(result.data)) {

                        if (!Y.checkNull(result.data.SeriesItem)) {
                            $('span.seriesName').text(result.data.SeriesItem.SeriesName);
                            $('span.itemName').text(result.data.SeriesItem.ItemName);
                        }

                        //动态插入th
                        if (result.data.title.length > 0) {
                            //先删除旧的然后再添加
                            $('.sizeTh').remove();
                            var tmpTr = "";
                            result.data.title.map(function (size, v) {
                                tmpTr = tmpTr + '<th id="" class="diy-td-w46 sizeTh" title="' + size.SizeName + '">' + size.SizeName + '</th>';
                            });
                            $('.SizeFlag').after(tmpTr);

                            //仓库 表格 2017 7 3
                            ///////////////////////////////////////
                            var stockHead = [];
                            var stockBody = [];
                            stockHead.push({ tdText: "尺码", c: 0, r: 0, tdHtml: '', tdId: '', tdClass: '' });
                            stockBody.push({ tdText: "库存", c: 0, r: 0, tdHtml: '', tdId: '', tdClass: '' });
                            result.data.title.map(function (title, k) {
                                stockHead.push({ tdText: title.SizeName, c: 0, r: 0, tdHtml: '', tdId: '', tdClass: '' });
                                stockBody.push({ tdText: "", c: 0, r: 0, tdHtml: '<span data-SizeID="' + title.SizeID + '"  data-SizeName="' + title.SizeName + '">&nbsp;</span>', tdId: '', tdClass: '' });
                            });
                           // console.log(stockHead)
                            tableControl.initThead('.stockTableBox table', [
                             {
                                 trClass: '', children: stockHead
                             }
                            ]);
                            tableControl.initTbody('.stockTableBox table', [
                             {
                                 trClass: '', children: stockBody
                             }
                            ], stockBody.length, null);

                            $(".stockBox").show().css("display", "inline-block");

                            ////end /////////////////////////////////////////////////////////
                            $(".infomation").show().css("display", "inline-block");
                        }
                      



                        if (result.data.group.length > 0) {
                            result.data.group.map(function (outShopItem, i) {
                                var model = outShopItem.list[0][0];
                                var pathQty = $.Enumerable.From(outShopItem.list[0])
                                    .Max(function(x) { return x.PathQty });
                                //尺码类型
                                var isbreaksize = "未知";
                                if (model.ISbreakSize == 0) {
                                    isbreaksize = "齐码";
                                } else {
                                    if (model.ISbreakSize == 1 && model.ISbreakSize_light == 0) {
                                        isbreaksize = "断码";
                                    } else if (model.ISbreakSize == 1 && model.ISbreakSize_light == 1) {
                                        isbreaksize = "轻断码";
                                    }
                                }

                                //尺码列前面的列
                                var stockType = model.InOrOutStock == 1 ? 2 : 0;//调入调出类型
                                var leftColumn = [
                                    { tdText: (model.CompanyID || ''), c: 0, r: stockType, tdHtml: '', tdId: '', tdClass: 'CompanyID hide' },
                                    { tdText: (model.StockID || ''), c: 0, r: stockType, tdHtml: '', tdId: model.StockID, tdClass: 'StockID hide' },
                                    { tdText: '', c: 0, r: stockType, tdHtml: '<div data-OutStockID="' + model.StockID + '" data-id=' + (i + 1) + ' class="ShopName" title="' + (model.ShopName || '') + '"><span class="glyphicon glyphicon-menu-hamburger"></span>' + (model.ShopName || '') + '</div>', tdId: 'row' + (i + 1), tdClass: '' },
                                    { tdText: (model.Saledays || 0), c: 0, r: stockType, tdHtml: '', tdId: '', tdClass: 'Saledays' },
                                    { tdText: (model.MaterialID || ''), c: 0, r: stockType, tdHtml: '', tdId: '', tdClass: 'hide MaterialID' },
                                    { tdText: (model.SKCCzpFlag || ''), c: 0, r: stockType, tdHtml: '', tdId: '', tdClass: 'SKCCzpFlag' },
                                    { tdText: (pathQty > 0 ? 'Y' : 'N'), c: 0, r: stockType, tdHtml: '', tdId: '', tdClass: 'PathQty' + (pathQty > 0 ? ' RedText' : ' BlueText') },
                                    { tdText: '', c: 0, r: stockType, tdHtml: '<div ExcelFlag="' + model.ExcelFlag + '" WeekSaleQty="' + (model.WeekSaleQty || 0) + '" class="liuzhuanzhou" data-default="' + (model.CirculWeek || '') + '">' + (model.CirculWeek || '') + '</div>', tdId: '', tdClass: '' },
                                    { tdText: (model.MoveOutFlag > 0 ? 'Y' : 'N'), c: 0, r: stockType, tdHtml: '', tdId: '', tdClass: 'MoveOutFlag' + (model.MoveOutFlag > 0 ? ' RedText' : ' BlueText') },
                                    { tdText: (isbreaksize), c: 0, r: 0, tdHtml: '', tdId: '', tdClass: 'Isbreaksize ' }
                                ];
                                var explainColumn = [{ tdText: '现/需', c: 0, r: 0, tdHtml: '', tdId: 'oldRow', tdClass: 'rowIndex' + (i + 1) }];


                                //动态尺码列
                                var sizeColumn = [];
                                var sizeArr = [];
                                var tmpModelArr = [];
                                result.data.title.map(function (title, k) {
                                    var isIn = false;
                                    outShopItem.list[0].map(function (sizeItem, j) {
                                        if (sizeItem.SizeName == title.SizeName) {
                                            sizeColumn.push({ tdText: "", c: 0, r: 0, tdHtml: '<span class="CanUseQty">' + sizeItem.SumQty + '</span>/<span class="MoveRequireQty">' + sizeItem.MoveRequireQty + '</span>', tdId: title.SizeName, tdClass: ' ' + (sizeItem.SizeCoreFlag == 1 ? "SizeCoreFlag" : "") });
                                            isIn = true;
                                            tmpModelArr.push({ SizeName: title.SizeName, CanUseQty: sizeItem.SumQty, SizeCoreFlag: (sizeItem.SizeCoreFlag || 0) });
                                        }
                                    });
                                    if (!isIn) {
                                        sizeColumn.push({ tdText: "0/0", c: 0, r: 0, tdHtml: '', tdId: title.SizeName, tdClass: 'CanUseQty' });
                                        tmpModelArr.push({ SizeName: title.SizeName, CanUseQty: 0, SizeCoreFlag: 0 });
                                    }
                                });
                                sizeArr.push(tmpModelArr);
                                //获取需求数量集合
                                var moveRequireArr = [];
                                tmpModelArr = [];
                                result.data.title.map(function (title, k) {
                                    var isIn = false;
                                    outShopItem.list[0].map(function (sizeItem, j) {
                                        if (sizeItem.SizeName == title.SizeName) {
                                            isIn = true;
                                            tmpModelArr.push({ SizeName: title.SizeName, MoveRequireQty: sizeItem.MoveRequireQty, SizeCoreFlag: (sizeItem.SizeCoreFlag || 0) });
                                        }
                                    });
                                    if (!isIn) {
                                        tmpModelArr.push({ SizeName: title.SizeName, MoveRequireQty: 0, SizeCoreFlag: 0 });
                                    }
                                });
                                moveRequireArr.push(tmpModelArr);
                                //统计
                                var totalCanUseQty = 0;
                                var totalMoveRequireQty = 0;
                                for (var o = 0; o < sizeArr[0].length; o++) {
                                    sizeArr.map(function (item, index) {
                                        totalCanUseQty += item[o].CanUseQty;
                                    });
                                    moveRequireArr.map(function (item, index) {
                                        totalMoveRequireQty += item[o].MoveRequireQty;
                                    });
                                }
                                var totalColumn = [{ tdText: totalCanUseQty + "/" + totalMoveRequireQty, c: 0, r: 0, tdHtml: '', tdId: '', tdClass: 'total' }];

                                //调出店铺列
                                var outStockIdHtml = "";
                                outShopItem.list.map(function (outStockItem, pp) {
                                    tmpModelArr = [];
                                    var sizeHtml = '<div style="display:none;" class="BindStock">';
                                    result.data.title.map(function (title, k) {
                                        var isIn = false;
                                        outStockItem.map(function (sizeItem, j) {
                                            if (sizeItem.SizeName == title.SizeName) {
                                                sizeHtml += '<div ' + (sizeItem.SizeCoreFlag == 1 ? ' class="SizeCoreFlag CanUseQty"' : 'class="CanUseQty"') + '><span class="SizeName">' + sizeItem.SizeName + '</span><span class="CanUseQty">' + sizeItem.NewCanUseQty + '</span></div>';
                                                isIn = true;
                                                tmpModelArr.push({ SizeName: title.SizeName, CanUseQty: sizeItem.NewCanUseQty, SizeCoreFlag: (sizeItem.SizeCoreFlag || 0) });
                                            }
                                        });
                                        if (!isIn) {
                                            sizeHtml += '<div class="CanUseQty"><span class="SizeName">' + title.SizeName + '</span><span class="CanUseQty">' + 0 + '</span></div>';
                                            tmpModelArr.push({ SizeName: title.SizeName, CanUseQty: 0, SizeCoreFlag: 0 });
                                        }
                                    });
                                    sizeHtml += "</div>";

                                    if (!Y.checkNull(outStockItem[0].OutShopName)) {
                                        outStockIdHtml += '<div data-OutStockID="' + outStockItem[0].OutStockID + '" class="ShopName ui-draggable divTitle ui-draggable-disabled" style="position: relative;">' + outStockItem[0].OutShopName + '<span style="" class="glyphicon glyphicon-remove-sign BindStockIcon"></span>' + sizeHtml + '</div>';
                                    }
                                    sizeArr.push(tmpModelArr);
                                });
                                var rightColumn = [{ tdText: '', c: 0, r: stockType, tdHtml: (outStockIdHtml || ''), tdId: '', tdClass: 'DropFlag' }];
                                //拼接表格
                                var allColumn = leftColumn.concat(explainColumn).concat(sizeColumn).concat(totalColumn).concat(rightColumn);
                                var tempTr = {
                                    trClass: (i % 2 == 0 ? 'gradeX footable-even' : 'gradeX footable-odd') + (model.InOrOutStock == 1 ? " NotAllowOut" : (model.InOrOutStock == 2 ? " NotAllowAll" : "")),
                                    children: allColumn
                                };
                                tBody.push(tempTr);

                                //调入店铺?加一行
                                if (model.InOrOutStock == 1) {
                                    var hideColumn = [{ tdText: 'newTr ', c: 0, r: 0, tdHtml: '', tdId: '', tdClass: 'newTr hide' }];
                                    var statusColumn = [{ tdText: 'afterStatus', c: 0, r: 0, tdHtml: '', tdId: '', tdClass: 'afterStatus' }];
                                    explainColumn = [{ tdText: '后', c: 0, r: 0, tdHtml: '', tdId: 'newRow', tdClass: 'rowIndex' + (i + 1) }];
                                    sizeColumn = [];
                                    for (var q = 0; q < sizeArr[0].length; q++) {
                                        var sizeName = "";
                                        var canUseQty = 0;
                                        var sizeCoreFlag = 0;
                                        sizeArr.map(function (item, index) {
                                            sizeName = item[q].SizeName;
                                            sizeCoreFlag = item[q].SizeCoreFlag;
                                            canUseQty += item[q].CanUseQty;
                                        });
                                        sizeColumn.push({ tdText: canUseQty, c: 0, r: 0, tdHtml: '', tdId: sizeName, tdClass: 'CanUseQty RedText' + (sizeCoreFlag == 1 ? " SizeCoreFlag" : "") });
                                    }
                                    //后 合计
                                    var totalQty = 0;
                                    for (var p = 0; p < sizeArr[0].length; p++) {
                                        sizeArr.map(function (item, index) {
                                            totalQty += item[p].CanUseQty;
                                        });
                                    }
                                    totalColumn = [{ tdText: totalQty, c: 0, r: 0, tdHtml: '', tdId: '', tdClass: 'total RedText' }];
                                    tempTr = {
                                        trClass: (i % 2 == 0 ? 'gradeX footable-even' : 'gradeX footable-odd') + (model.InOrOutStock == 1 ? " NotAllowOut" : (model.InOrOutStock == 2 ? " NotAllowAll" : "")),
                                        children: hideColumn.concat(statusColumn).concat(explainColumn).concat(sizeColumn).concat(totalColumn)
                                    };
                                    tBody.push(tempTr);
                                }
                            });
                        }
                        rScroll();
                    }

                    if (tBody.length <= 0) {
                        $(".stockBox").hide();
                        $(".infomation").hide();
                    }

                    tableControl.initTbody('.footable', (tBody.length > 0 ? tBody : null), 13, null);

                  

                    //拖拽
                    $('.ShopName').draggable({
                        cursor: "move",
                        helper: function (event) {
                            return $(this).prop('outerHTML');
                        },
                        start: function () {
                            dragTr = $(this).parents('tr');
                        }
                    });

                    //释放
                    $('.DropFlag').droppable({
                        hoverClass: "DropTd",
                        tolerance: "custom",
                        drop: function (event, ui) {
                            var source = ui.draggable.clone();
                            source.find('span').remove();
                            source.addClass('divTitle');

                            var dropTr = $(this).parents('tr');

                            //拖动行和接收行的tr(组)标志
                            var dragTrIndex = dragTr.find('#oldRow').prop("class");
                            var dropTrIndex = dropTr.find('#oldRow').prop("class");

                            if (dragTrIndex == dropTrIndex) {
                                swal("不允许调拨给自己", '', 'error');
                                return false;
                            }

                            //状态列之前的列全部合并
                            dropTr.find('td:lt(' + iColumn + '),td:last').attr("rowspan", "2");

                            //拖动行和接受行-所有尺码td
                            var dragTds = dragTr.find('.CanUseQty');
                            var dropTds = dropTr.find('.CanUseQty');
                            //只有一个行标记，说明没有加新tr，需要新插入一个
                            if ($("." + dropTrIndex).length < 2) {
                                //构造新的一行的tr
                                var newTr2 = dropTr.clone();
                                var tmpTd = newTr2.find('#oldRow');
                                tmpTd.text("后");
                                tmpTd.attr('id', "newRow");
                                //添加一行做行标志（好像有newRow之后可以删了）
                                var newTrHtml = '<td id="" class="newTr hide" title="newTr">newTr</td>';
                                //调拨后尺码状态
                                var statusTrHtml = '<td id="" class="afterStatus" title="afterStatus"></td>';
                                newTrHtml += statusTrHtml;
                                newTrHtml += tmpTd.prop('outerHTML');

                                var tmpTotal = 0;
                                //更新尺码
                                for (var j3 = 0; j3 < dragTds.length; j3++) {
                                    var sum3 = parseInt(dragTds.eq(j3).text()) + parseInt(dropTds.eq(j3).text());
                                    newTrHtml += '<td id="' + dragTds.eq(j3).prop('id') + '" class="CanUseQty RedText">' + sum3 + '</td>';
                                    tmpTotal += sum3;//累加尺码
                                }
                                //更新合计
                                newTrHtml += '<td id="" class="total RedText">' + tmpTotal + '</td>';
                                newTr2.html(newTrHtml);
                                //新的一行插入到表格
                                dropTr.after(newTr2);
                            } else {//有两个行标记的，就是已经加了行了，直接修改就行
                                var newTr1 = $("." + dropTrIndex).parents('tr').find('#newRow').parents('tr');
                                var newTds5 = newTr1.find('.CanUseQty');
                                var tmpTotal2 = 0;
                                //更新尺码
                                for (var k2 = 0; k2 < newTds5.length; k2++) {
                                    var tmp1 = parseInt(dragTds.eq(k2).text()) + parseInt(newTds5.eq(k2).text());
                                    newTds5.eq(k2).text(tmp1);
                                    tmpTotal2 += tmp1;
                                }
                                //更新合计
                                newTr1.find('.total').text(tmpTotal2);
                            }
                            //拖放之后的新行
                            var newTr = $("." + dropTrIndex).parents('tr').find('#newRow').parents('tr');
                            //流转周
                            var newTotal = parseInt(newTr.find('.total').text());
                            var weekSaleQty = parseInt(dropTr.find('.liuzhuanzhou').attr('weeksaleqty'));
                            var result1 = (newTotal / weekSaleQty).toFixed(1);
                            if ((newTotal == 0 || weekSaleQty == 0 || result1 == 0)) {
                                dropTr.find('.liuzhuanzhou').text(dropTr.find('.liuzhuanzhou').attr('data-default'));
                            } else {
                                dropTr.find('.liuzhuanzhou').text(result1);
                            }

                            //创建一个图标
                            $('<span></span>',
                            {
                                style: '', "class": "glyphicon glyphicon-remove-sign",
                                click: function () {
                                    //调出店铺对应的列表的行(因为DragTr只能记录最近操作的一个，这里用店铺反找)
                                    var delDragTr = $('div[data-outstockid="' + $(source).attr('data-outstockid') + '"]').find('.glyphicon-menu-hamburger').parents('tr');
                                    //所有尺码td
                                    var delDragTds = delDragTr.find('.CanUseQty');
                                    //新加的红色那行的行尺码td
                                    var newTds2 = newTr.find('.CanUseQty');

                                    var total = 0;
                                    //更新尺码和对应合计
                                    for (var m = 0; m < newTds2.length; m++) {
                                        var t = parseInt(newTds2.eq(m).text()) - parseInt(delDragTds.eq(m).text());
                                        newTds2.eq(m).text(t);
                                        total += t;
                                    }
                                    newTr.find('.total').text(total);

                                    //删除拖动块
                                    source.remove();

                                    //调拨后尺码状态
                                    newTr.find('td.afterStatus').text("齐码");
                                    var targetTds2 = dropTr.find('.CanUseQty');
                                    for (var n = 0; n < targetTds2.length; n++) {
                                        if (targetTds2.eq(n).hasClass("SizeCoreFlag") && (parseInt(targetTds2.eq(n).text()) + parseInt(newTds2.eq(n).text()) == 0)) {
                                            newTr.find('td.afterStatus').text("断码");
                                            break;;
                                        }
                                    }

                                    //流转周1
                                    var tmpTotal3 = parseInt(newTr.find('.total').text());
                                    var weekSaleQty2 = parseInt(dropTr.find('.liuzhuanzhou').attr('weeksaleqty'));
                                    var r4 = (tmpTotal3 / weekSaleQty2).toFixed(1);
                                    if (tmpTotal3 == 0 || weekSaleQty2 == 0 || r4 == 0) {
                                        dropTr.find('.liuzhuanzhou').text(dropTr.find('.liuzhuanzhou').attr('data-default'));
                                    } else {
                                        dropTr.find('.liuzhuanzhou').text(r4);
                                    }

                                    //重新开启
                                    delDragTr.find('.ShopName').draggable({ disabled: false });
                                    if (delDragTr.find('td.MoveOutFlag').text() == "Y") {
                                        delDragTr.find('.DropFlag').droppable({ disabled: true });
                                    } else {
                                        delDragTr.find('.DropFlag').droppable({ disabled: false });
                                    }

                                    //还原样式和事件
                                    $("." + delDragTr.find('td#oldRow').prop('class')).parents('tr').removeClass('NotAllowAll');
                                    //没有调出店铺之后，还原现场
                                    if (dropTr.find('.DropFlag').text() == "") {
                                        newTr.remove();
                                        //直接去掉接收行所有的合并
                                        dropTr.find('td').removeAttr("rowspan");

                                        //在途的不能回复到自由拖拽的状态
                                        if (dropTr.find('td.PathQty').text() == "N" && dropTr.find('td.Saledays').text() > 14) {
                                            dropTr.find('.ShopName').draggable({ disabled: false });
                                            $("." + dropTrIndex).parents('tr').removeClass('NotAllowOut');
                                        }
                                        //复原流转周为0（不显示0）
                                        dropTr.find('.liuzhuanzhou').text(dropTr.find('.liuzhuanzhou').attr('data-default'));
                                    }


                                    //====================================
                                }
                            }).appendTo(source);

                            //把拖拉的td放进调出店铺的div
                            $(this).append(source);

                            //调拨后尺码状态
                            newTr.find('td.afterStatus').text("齐码");
                            var targetTds = dropTr.find('.CanUseQty');
                            var newTds4 = newTr.find('.CanUseQty');
                            for (var k = 0; k < targetTds.length; k++) {
                                if (targetTds.eq(k).hasClass("SizeCoreFlag")) {
                                    if (parseInt(targetTds.eq(k).text()) + parseInt(newTds4.eq(k).text()) == 0) {
                                        newTr.find('td.afterStatus').text("断码");
                                        break;
                                    }
                                }
                            }

                            //禁止拖拽
                            dropTr.find('.ShopName').draggable({ disabled: true });
                            dragTr.find('.ShopName').draggable({ disabled: true });

                            $("." + dropTrIndex).parents('tr').addClass('NotAllowOut');
                            $("." + dragTrIndex).parents('tr').addClass('NotAllowAll');
                            //调出的不允许再接收
                            dragTr.find('.DropFlag').droppable({ disabled: true });

                            //写个标志以便减少保存的行
                            dragTr.addClass("modified");
                            dropTr.addClass("modified");
                        }
                    });

                    $('.BindStockIcon').click(function () {
                        //获取当前行
                        var currentTr = $(this).parents('tr');
                        //获取红色的调拨统计行
                        var redTr = $('.' + currentTr.find('td#oldRow').prop('class')).parents('tr').find('.newTr').parents('tr');
                        //获取红色合计行的td
                        var redTds = redTr.find('.CanUseQty');
                        //获取被删的div里的尺码
                        var divs = $(this).parents('.ShopName').find('div.CanUseQty');
                        //更新尺码
                        var sum = 0;
                        for (var u = 0; u < redTds.length; u++) {
                            var a = redTds.eq(u).text() - divs.eq(u).find('span.CanUseQty').text();
                            redTds.eq(u).text(a);
                            sum += a;
                        }
                        //更新合计
                        redTr.find('.total').text(sum);

                        //流转周
                        var tmpTotal = parseInt(redTr.find('.total').text());
                        var weekSaleQty = parseInt(currentTr.find('.liuzhuanzhou').attr('weeksaleqty'));
                        var r4 = (tmpTotal / weekSaleQty).toFixed(1);
                        if ((tmpTotal == 0 || weekSaleQty == 0 || r4 == 0)) {
                            currentTr.find('.liuzhuanzhou').text(currentTr.find('.liuzhuanzhou').attr('data-default'));
                        } else {
                            currentTr.find('.liuzhuanzhou').text(r4);
                        }

                        //计算调拨后尺码状态
                        redTr.find('td.afterStatus').text("齐码");
                        for (var ii = 0; ii < redTds.length; ii++) {
                            if (redTds.eq(ii).hasClass("SizeCoreFlag") && redTds.eq(ii).text() == 0) {
                                redTr.find('td.afterStatus').text("断码");
                                break;
                            }
                        }

                        //恢复状态
                        var newTr2 = $("#" + $(this).parents('div.ShopName').attr('data-OutStockID')).parents('tr');
                        //删掉被调用行的样式
                        newTr2.removeClass('NotAllowAll');
                        newTr2.find('.ShopName ').draggable({ disabled: false });
                        if (newTr2.find('td.MoveOutFlag').text() == "Y") {
                            newTr2.find('.DropFlag').droppable({ disabled: true });
                        } else {
                            newTr2.find('.DropFlag').droppable({ disabled: false });
                        }


                        //删除调出店铺
                        $(this).parent('.ShopName').remove();

                        //调整布局
                        if (currentTr.find('td.DropFlag').html() == "") {
                            redTr.remove();
                            currentTr.find('td').removeAttr("rowspan");
                            redTr.find('td.afterStatus').text("");
                            //在途跟调出都不能回复到自由拖拽
                            if (currentTr.find('.PathQty').text() == "N" && currentTr.find('td.Saledays').text() > 14) {
                                currentTr.removeClass('NotAllowOut');
                                currentTr.find('.ShopName ').draggable({ disabled: false });
                            }
                            currentTr.find('.liuzhuanzhou').text(currentTr.find('.liuzhuanzhou').attr('data-default'));
                        }

                        currentTr.addClass("modified");
                        newTr2.addClass("modified");
                    });

                    //统一设置绑定时的"调拨后尺码状态"
                    $('.newTr').parents('tr').map(function () {
                        var newTds = $(this).find('.CanUseQty');
                        //var oldTr = $("." + $(this).find('#newRow').prop('class')).parents('tr').find('#oldRow').parents('tr');
                        $(this).find('.afterStatus').text("齐码");
                        for (var i = 0; i < newTds.length; i++) {
                            if (newTds.eq(i).hasClass('SizeCoreFlag') && (newTds.eq(i).text() == "0" || newTds.eq(i).text() == "")) {
                                $(this).find('.afterStatus').text("断码");
                                break;
                            }
                        }
                    });


                    //当Saledays <=14，则不允许作为调出方
                    $('.Saledays:textLessThanOrEqualTo(14)').parents('tr').addClass("NotAllowOut");
                    //在途不能调出只能调入
                    $('.PathQty.RedText').parents('tr').addClass("NotAllowOut");
                    //调出
                    $('.MoveOutFlag.RedText').parents('tr').addClass('NotAllowIn');

                    //不能调出只能调入
                    $('.NotAllowOut').find('.ShopName ').draggable({ disabled: true });
                    //不能调入只能调出
                    $('.NotAllowIn').find('.DropFlag ').droppable({ disabled: true });
                    //不能接收不能调出
                    $('.NotAllowAll').find('.DropFlag').droppable({ disabled: true });
                    $('.NotAllowAll').find('.ShopName ').draggable({ disabled: true });

                    //流转周
                    $('.newTr').parents('tr').map(function () {
                        var rowIndex = $(this).find('#newRow').prop('class');
                        var oldTr = $("." + rowIndex).parents('tr').find('#oldRow').parents('tr');

                        var weekSaleQty = oldTr.find('.liuzhuanzhou').attr('weeksaleqty');
                        var tmpTotal = $(this).find('.total').text();

                        if ((parseInt(tmpTotal) == 0 || parseInt(weekSaleQty) == 0)) {
                            oldTr.find('.liuzhuanzhou').text(oldTr.find('.liuzhuanzhou').attr('data-default'));
                        } else {
                            oldTr.find('.liuzhuanzhou').text((parseInt(tmpTotal) / parseInt(weekSaleQty)).toFixed(1));
                        }

                    });

                    //判断是否已经导出
                    if ($('.liuzhuanzhou[ExcelFlag="1"]').length != 0) {
                        $('#btn-save').attr("disabled", "disabled");
                    }

                    //需求大于0的红色
                    $('.CanUseQty:textMoreThan(0)').addClass('RedText');
                    $('.MoveRequireQty:textMoreThan(0)').addClass('RedText');

                });
            }


            //仓库change 2017 7 3
            $("#search-stockID").on("change", function () {
                //获取列表中的数据
                var _CompanyID = $("#pageList .CompanyID").eq(0).text();
                var _StockID = $(this).val();
                var _MaterialID = $("#pageList .MaterialID").eq(0).text();
                if (Y.checkNull(_StockID)) {
                    $(".stockTableBox table").find("td span").html("&nbsp;");
                    return;
                }
                if (Y.checkNull(_MaterialID))
                {
                    swal("获取数据失败，请刷新页面重试！", '', 'error');
                    return;
                }
                if (!Y.checkNull(_CompanyID) && !Y.checkNull(_StockID) && !Y.checkNull(_MaterialID)) {
                    layer.msg('玩命加载中……', { icon: 16, shade: 0.5, time: 0, maxWidth: 200 });
                    Y.API2('NewOdsErpTmpCalcStock', "GetStockSizeCanUseQty", { CompanyID: _CompanyID, StockID: _StockID, MaterialID: _MaterialID },
                    function (data) {
                        layer.closeAll('dialog');
                        if (data.Success == false) {
                            swal(data.Message, '', 'error');
                        } else {
                            $(".stockTableBox table").find("td span").html("&nbsp;");
                            if (data.length>0){
                            data.map(function (size, i) {
                                $(".stockTableBox table").find("td span[data-SizeName='" + size.SizeName + "']").text(size.CanUseQty);
                            });
                            }
                        }
                    });
                }
            });

            //查询按钮
            $('.btns-container').on('click', '#btn-search', function () {
                var materialId = $('#search-MaterialID').val();
                if (materialId == "") {
                    swal("请填写货号！", '', 'error');
                    return false;
                }
                //
                $('.stockTableBox td').not($('.stockTableBox td:first')).text('');
                $('#search-stockID option').eq(0).prop('selected', true);

                page = 1;
                loadList();
            });

            var msgTxt = "";
            var msgType = "success";
            //保存操作
            $('.btns-container').on('click', '#btn-save', function () {
                var dataList = [];
                var materialId = "";
                //遍历所有要提交的行
                $('#pageList').find('.glyphicon-menu-hamburger').parents('tr').each(function () {
                    var outStockIdList = [];
                    //遍历所有调出店铺ID
                    $(this).find('.DropFlag').find("div").each(function () {
                        outStockIdList.push({
                            OutStockID: $(this).attr('data-OutStockID')
                        });
                    });

                    var data = {};
                    //data.CompanyID = $(this).find(".CompanyID").text();
                    //data.MaterialID = $(this).find(".MaterialID").text();
                    materialId = $(this).find(".MaterialID").text();
                    data.InStockID = $(this).find(".StockID").text();
                    data.OutStockIDList = outStockIdList;
                    dataList.push(data);
                });


                layer.msg('玩命加载中……', {icon: 16, shade: 0.5, time: 0, maxWidth: 200}, function () {
                    swal({ title: msgTxt, type: msgType, closeOnConfirm: true }, function () { loadList(); });
                });
                    Y.API2('NewOdsErpTmpCalcStock',"UpdateMvJobMessage",
                        {
                            MaterialID: materialId,
                            list: dataList
                        },
                    function (data) {
                        if (data.Success == false) {
                            msgType = "error";
                            msgTxt = data.Message;
                        } else {
                            msgType = "success";
                            msgTxt = "保存成功";
                        }
                        layer.closeAll('dialog');
                    });
            });

            //导入
            $(".btns-container").on("click", '#downloadAllocation', function () {

                swal({
                    title: "您确定要下载吗？",
                    text: "本操作属于敏感操作，请认真考虑清楚",
                    type: "warning",
                    showCancelButton: true,
                    closeOnConfirm: false,
                    confirmButtonText: "确定下载",
                    cancelButtonText: "暂不下载",
                    confirmButtonColor: "#ec6c62"
                }, function () {

                    var UserID = JSON.parse(window.sessionStorage.getItem('login-info'));
                    if (!Y.checkNull(UserID))
                        UserID = UserID.UserId;
                    var conditionsArr = [];
                    conditionsArr.push({ column: "Operator", value: UserID, operator: "=", connector: "and" });
                    conditionsArr = JSON.stringify(conditionsArr);
                    var tempParam = {};
                    tempParam.filename = "调出店铺";
                    tempParam.filetype = "NEWODSERPTMPCALCSTOCK";
                    tempParam.conditions = encodeURIComponent(conditionsArr);
                    var t = $.Export(tempParam);

                    //swal("下载完毕!");
                    swal.close();
                    $('#btn-save').attr("disabled", "disabled");
                });
            });

            //loadList();

            $('#search-Shop').boxDrop({ width: 120 });
            $('#search-Shop').on("boxdrop_open", function () {
                $('#search-Shop').boxDrop("load", { ParentAreaID: $("#search-ParentAreaID").val() });
            });


       
        });

    </script>
</asp:Content>

